package com.tx.apigateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;

/**
 * 跨域配置
 * CORS:跨域资源共享
 */
@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter(){
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        final CorsConfiguration config = new CorsConfiguration();
        // 是否支持cookie跨域
        config.setAllowCredentials(true);
        // 放置原始域,全部允许或者http://www.a.com
        config.setAllowedOrigins(Arrays.asList("*"));
        // 允许头
        config.setAllowedHeaders(Arrays.asList("*"));
        // 允许的方法,GET/POST
        config.setAllowedMethods(Arrays.asList("*"));
        // 缓存时间,在缓存时间内对于相同的跨域请求将不再进行检查
        config.setMaxAge(300l);
        // 对那些域名进行配置
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}
